package com.netease.pluginproject;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;

import com.netease.stander.ActivityInterface;

import java.lang.reflect.Constructor;

public class ProxyActivity extends Activity {
    /**
     * 获取资源方法
     * @return 插件apk的布局资源
     */
    @Override
    public Resources getResources() {
        return PluginManager.getInstance(this).getResources();
    }

    /**
     * 获取类的方法
     * @return 插件apk的类
     */
    @Override
    public ClassLoader getClassLoader() {
        return PluginManager.getInstance(this).getDexClassLoader();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //真正加载插件里面的activity   com.netease.plugin_package.PluginActivity
        String className = getIntent().getStringExtra("className");
        try{
            //根据包名加载大概的类
            Class mPluginActivityClass = getClassLoader().loadClass(className);
            //根据大概类获取构造方法
            Constructor constructor = mPluginActivityClass.getConstructor(new Class[]{});
            //根据构造方法来获取具体的类
            Object mPluginActivity = constructor.newInstance(new Object[]{});
            //强制转换为父类的实现接口
            ActivityInterface activityInterface= (ActivityInterface) mPluginActivity;
            //向插件注入宿主环境
            activityInterface.insertAppContext(this);

            Bundle bundle = new Bundle();
            bundle.putString("appName", "我是宿主传递过来的信息");

            // 执行插件里面的onCreate方法
            activityInterface.onCreate(bundle);

        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public void startActivity(Intent intent) {
        String className = intent.getStringExtra("className");

        Intent proxyIntent = new Intent(this, ProxyActivity.class);
        proxyIntent.putExtra("className",className);//包名+TestActivity
        super.startActivity(proxyIntent);
    }
}